import time
from chaojiying import crack_verification
# 破解验证码

import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from PIL import Image


driver = webdriver.Chrome()
driver.maximize_window()

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
}
res_citylist = requests.get("https://www.lianjia.com/city/", headers=headers, allow_redirects=False)
if res_citylist.status_code == 302:
    redirect_url = res_citylist.headers["Location"]  # 获取重定向后的url
    driver.get(redirect_url)  # 打开重定向后的url
    time.sleep(1)
    captcha_btn = driver.find_element(By.ID, 'captcha')  # 找到验证码按钮
    captcha_btn.click()  # 点击验证码按钮
    time.sleep(0.5)
    captcha_box = driver.find_element(By.CLASS_NAME, "image-code")  # 找到验证码图片
    x1 = captcha_box.rect["x"]  # 获取验证码图片的左上角x坐标
    y1 = captcha_box.rect["y"]  # 获取验证码图片的左上角y坐标
    x2 = captcha_box.rect["x"] + captcha_box.rect["width"]  # 获取验证码图片的右下角x坐标
    y2 = captcha_box.rect["y"] + captcha_box.rect["height"]  # 获取验证码图片的右下角y坐标

    print(captcha_box.location, captcha_box.size, captcha_box.rect)  # 获取验证码位置和大小
    screen = driver.save_screenshot("screen.png")  # 截屏
    screen_img = Image.open("screen.png")  # 打开截屏
    rect_img = screen_img.crop((x1, y1, x2, y2))  # 裁剪验证码图片
    rect_img.save("rect.png")  # 保存验证码图片
    # dddd 带带弟弟解决方案
    # code = parse_code("rect.png")
    code = crack_verification("rect.png", 4004)  # 调用破解验证码函数

    time.sleep(1)
    input_tag = driver.find_element(By.CSS_SELECTOR, ".input")  # 找到输入框
    input_tag.send_keys(code)  # 输入验证码

    time.sleep(10)
    driver.quit()  # 关闭浏览器
